<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2019/7/17
 * Time: 10:43
 */

namespace app\api\controller\v8;


use app\api\controller\v2\Auth;
use app\astro\controller\Index as AstroIndex;
use app\common\cachemodel\FortuneCache;
use app\common\cachemodel\RectificationResult;
use app\common\lib\PushQueue;
use app\common\lib\Rectification as RectificationLib;
use app\common\lib\SensorsData;
use app\common\lib\Util;
use app\common\model\Goods;
use app\common\model\Recode;
use app\common\model\Rectification as RectificationModel;
use DateTime;
use DateTimeZone;
use Exception;
use think\Cache;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\Log;
use think\Log as TpLog;
use think\response\Json;

/**
 * 校准生辰（时间以字符串的格式传递给服务器）
 * Class Rectification
 * @package app\api\controller\v8
 */
class Rectification extends Auth
{
    protected $noNeedJudgeSummer = ['香港特别行政区', '澳门特别行政区', '台湾省', '北美洲', '大洋洲', '非洲', '南美洲', '欧洲', '亚洲', ''];

    /**
     * @title 查看历史记录 加入订单id字段
     * @method GET
     * @desc /rectifications
     * @readme /doc/md/rectification/index.md
     */
    public function index()
    {
        if (!$this->request->isGet())
        {
            return show(config('code.error'), '未知操作');
        }
        // 用户id
        $uid = (int)$this->user['id'];

        // 页码
        $page = input('get.page/d', 1);
        // 要查询的字段
        $field = 'id,status,start_time,end_time,create_time';
        $where = ['uid' => $uid, 'is_del' => 0];
        $order = 'id DESC';
        try
        {
            // 判断是否是applePay
            if ($this->is_apple_pay)
            {
                $goods = $this->apple_goods['rec_goods'][0];
            } else
            {
                $goods = (new Goods())->getGoodsRec(['id' => 1]);
            }

            $data = (new RectificationModel())
                ->field($field)
                ->where($where)
                ->order($order)
                ->group('id')
                ->paginate(10, false, ['page' => $page])->toArray();
        }
        catch (Exception $e)
        {
            $goods['id'] = 1;
            $data['data'] = [];
        }

        if (!empty($data['data']))
        {
            // 重组redis 为逗号隔开字符串
            $reids = implode(',', array_unique(array_column($data['data'], 'id')));
            // 获取当前校准生辰的订单信息
            $orders = Db::query("SELECT o.id,o.trade_type,o.order_id,o.reid FROM app_orders o inner join (SELECT substring_index(group_concat(id order by id desc),',',1) id from app_orders  group by reid) o2 on o.id=o2.id where o.reid in ($reids)");
            // 重组数组 以reid为key
            $orders = array_column($orders, null, 'reid');

            foreach ($data['data'] as $k => $v)
            {
                // 获取活动折扣
                $activeDiscount = active($goods['id']);

                if ($activeDiscount['discount'] && !$this->is_apple_pay)
                {
                    $data['data'][$k]['now_prize'] = sprintf('%.2f', $goods['now_prize'] * $activeDiscount['discount']);
                } else
                {
                    $data['data'][$k]['now_prize'] = sprintf("%.2f", $goods['now_prize']);
                }

                [$recodeTIme, $startHourMinute] = explode(',', date('Y-m-d,H:i', $v['start_time']));
                $endHourMinute = date('H:i', $v['end_time']);

                $data['data'][$k]['id'] = (int)$v['id'];
                $data['data'][$k]['status'] = (int)$v['status'];
                $data['data'][$k]['or_prize'] = sprintf("%.2f", $goods['or_prize']);
                $data['data'][$k]['order_id'] = $orders[$v['id']]['order_id'] ?? null;
                $data['data'][$k]['trade_type'] = isset($orders[$v['id']]['trade_type']) ? (int)$orders[$v['id']]['trade_type'] : 0;
                $data['data'][$k]['recode_time'] = $recodeTIme;
                $data['data'][$k]['start_time'] = $startHourMinute;
                $data['data'][$k]['end_time'] = $endHourMinute;
                $data['data'][$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            }

            return show(config('code.success'), '加载成功', $data);

        }

        return show(config('code.success'), '您还没有校正过哦，去矫正吧~');
    }

    /**
     * @title 查看历史  加入订单id字段######
     * @method GET
     * @desc /rectification
     * @readme /doc/md/rectification/read.md
     */
    public function read()
    {
        if (!$this->request->isGet())
        {
            return show(config('code.error'), '未知操作');
        }
        // 校准生辰id
        $id = input('get.reid/d', 0);
        // 要排除的字段
        $field = ['uid', 'update_time'];

        if (!$id)
        {
            return show(config('code.error'), '数据不存在');
        }

        try
        {
            // 判断是否是applePay
            if ($this->is_apple_pay)
            {
                $goods = $this->apple_goods['rec_goods'][0];
            } else
            {
                $goods = (new Goods())->getGoodsRec(['id' => 1]);
            }
        }
        catch (Exception $e)
        {
            return show(config('code.error'), '获取校准生辰商品信息失败');
        }

        if (!$goods || empty($goods))
        {
            return show(config('code.error'), '商品不存在');
        }
        try
        {
            $data = RectificationModel::get(['id' => $id]);

            if (!$data || $data['uid'] != $this->user['id'])
            {
                return show(config('code.error'), '数据不存在');
            }

            $data->hidden($field);
            // 事件
            $data['events'] = $data->events()->order('id ASC')->select();
            // 校正结果
            $data['result'] = $data->result()->field('id,time,score,status')->select();

            $data['rname'] = $data->recode()->column('name')[0];

            $return = 0;

            // 因订单删除后,消息中心还可以进入校准生辰详情,所以要确保,$orders有值
            // 获取已支付的订单信息
            $orderFields = 'order_id,trade_type,pay_time,return_time,total_amount';
            $orders = RectificationModel::hasWhere('Orders', ['reid' => $id, 'pay_time' => ['>', 0]])->field($orderFields)->find();
            if (!$orders)
            {
                $orders = RectificationModel::hasWhere('Orders', ['reid' => $id, 'is_del' => 0])->field($orderFields)->find();
            }

            // 将数据对象转为数组
            $data = $data->toArray();

            $data['recode_time'] = Util::is_strtotime($data['start_time']) == false ? date('Y-m-d', strtotime($data['start_time'])) : date('Y-m-d', $data['start_time']);
            $data['start_time'] = Util::is_strtotime($data['start_time']) == false ? date('H:i', strtotime($data['start_time'])) : date('H:i', $data['start_time']);
            $data['end_time'] = Util::is_strtotime($data['end_time']) == false ? date('H:i', strtotime($data['end_time'])) : date('H:i', $data['end_time']);
            $data['create_time'] = date('Y-m-d H:i:s', $data['create_time']);

            $data['result_time'] = $data['result_time'] <= 0 ? '' : date('Y-m-d H:i:s', $data['result_time']);

            // 更改结果时间为字符串格式  时-分
            foreach ($data['result'] as $ke => $ev)
            {
                $data['result'][$ke]['time'] = date('Y/m.d H:i', $ev['time']);
            }

            // 更改事件时间为字符串格式  年-月
            foreach ($data['events'] as $ke => $ev)
            {
                $data['events'][$ke]['time'] = date('Y-m', $ev['time']);
            }

            // 获取活动折扣，现价进行处理
            $activeDiscount = active($goods['id']);
            if ($activeDiscount['discount'] && !$this->is_apple_pay)
            {
                $data['now_prize'] = sprintf("%.2f", $goods['now_prize'] * $activeDiscount['discount']);
            } else
            {
                $data['now_prize'] = sprintf("%.2f", $goods['now_prize']);
            }
            $data['or_prize'] = sprintf("%.2f", $goods['or_prize']);
            if ($orders)
            {
                $return = $orders->return_time;
                $data['orders'] = [
                    'pay_time' => date('Y-m-d H:i:s', $orders->pay_time),
                    'order_id' => $orders->order_id,
                    'trade_type' => $orders->trade_type,
                    'total_amount' => $orders->total_amount,
                ];
                $data['now_prize'] = $orders['total_amount'];
            } else
            {
                $data['orders'] = [
                    'pay_time' => 0,
                    'order_id' => '',
                    'trade_type' => 0,
                    'total_amount' => $data['now_prize'],
                ];
            }
            $data['return_time'] = $return;
        }
        catch (Exception $e)
        {
            TpLog::write('readError:' . $e->getMessage(), 'error');
            return show(config('code.error'), '校准生辰信息获取失败');
        }

        unset($data['orders']['status'], $data['orders']['return_time']);
        return show(config('code.success'), '查看成功', $data);
    }

    /**
     * @title 提交校准生辰
     * @method POST
     * @desc /rectification
     * @readme /doc/md/rectification/save.md
     * @return Json
     * @throws Exception
     */
    public function save()
    {
        if (!$this->request->isPost())
        {
            return show(config('code.error'), '未知操作');
        }
        // 档案id
        $rid = input('post.rid/d');
        // 校正开始时间 时间字符串 如：2019-07-17 00:00:00
        $start_time = input('post.start_time/s', null);
        // 校正结束时间 时间字符串 如：2019-07-17 01:00:00
        $end_time = input('post.end_time/s', null);

        if (strtotime($start_time) === false || strtotime($end_time) === false)
        {
            return show(config('code.error'), '请检查时间是否正确');
        }
        $startTimeInter = strtotime($start_time);
        $endTimeInter = strtotime($end_time);

        $timeDiff = $endTimeInter - $startTimeInter;

        if ($timeDiff < 0)
        {
            return show(config('code.error'), '开始时间不能大于结束时间');
        }

        if ($timeDiff == 0)
        {
            return show(config('code.error'), '开始时间不能等于结束时间');
        }

        if ($timeDiff > 7200)
        {
            return show(config('code.error'), '校正范围不可超过两小时');
        }

        // 校准生辰事件json
        $events = input('post.events/s');

        $ev = json_decode($events, true);

        $nowTime = $this->request->time();

        foreach ($ev as $k => $v)
        {
            $vTime = isset($v['time']) ? strtotime($v['time']) : 0;
            /**
             * 校验 事件时间不能大于当前时间 && 事件时间不能小于出生时间
             */
            if ($vTime > $nowTime || $vTime < $startTimeInter)
            {
                return show(config('code.error'), '请检查事件的时间是否正确选择');
            }
        }
        // json 转 array
        $events_array = json_decode($events, true);
        // 用户id
        $uid = (int)$this->user['id'];
        // 检测传参
        if (!$uid || !$rid || !$events || empty($events_array))
        {
            return show(config('code.error'), '请检查事件是否正确填写');
        }
        $recode = (new Recode())->getRecode(['id' => $rid]);
        if (!$recode || $recode['uid'] != $this->user['id'])
        {
            return show(config('code.error'), '档案不存在');
        }
        if ($recode['isself'] != 1)
        {
            return show(config('code.error'), '当前仅限校正自己的档案');
        }

        // 矫正范围的中点时间
        $birth_time_mid = ($startTimeInter + $endTimeInter) / 2;

        // 有效事件判断
        $event_array = (new RectificationLib())->getValidEvents($events_array, $birth_time_mid, $recode);

        // 初始化有效事件数量
        $vaild_num = 0;
        // 有效事件++
        foreach ($event_array as $ea)
        {
            if ($ea['status'] == 1) $vaild_num++;
        }

        //判断是否是applePay
        if ($this->is_apple_pay)
        {
            $goods = $this->apple_goods['rec_goods'][0];
        } else
        {
            $goods = (new Goods())->getGoodsRec(['id' => 1]);
        }

        if (!$goods || empty($goods))
        {
            return show(config('code.error'), '商品不存在');
        }

        // 获取活动折扣
        $activeDiscount = active($goods['id']);
        if ($activeDiscount['discount'] && !$this->is_apple_pay)
        {
            $goods['now_prize'] = sprintf('%.2f', $goods['now_prize'] * $activeDiscount['discount']);
        }

        $ret = [
            'status' => 0,
            'or_amount' => sprintf('%.2f', $goods['or_prize']),
            'total_amount' => sprintf('%.2f', $goods['now_prize']),
            'reid' => 0,
        ];

        // 入库  付款后 加入计算队列
        try
        {
            $insert_data = [
                'uid' => $uid,
                'rid' => $rid,
                'start_time' => $startTimeInter,
                'end_time' => $endTimeInter,
                'create_time' => time()
            ];
            $rectification = new \app\common\cachemodel\Rectification();
            $id = $rectification->saveRec($this->user['id'], 0, $insert_data, $event_array);
//            // 存入校准生辰表
//            $rectification->isUpdate(false)->allowField(true)->save($insert_data);
//
//            $id = $rectification->id;
//            // 存入校准生辰事件表
//            $rectification->events()->saveAll($event_array);
        }
        catch (Exception $e)
        {
            return show(config('code.error'), $e->getMessage(), [], 500);
        }

        $ret['reid'] = (int)($id);

        if ($vaild_num < 1)
        {
            return show(config('code.success'), '无有效事件，会导致校正失败，请继续添加', $ret);
        }

        if ($vaild_num < 3)
        {
            $ret['status'] = 1;

            return show(config('code.success'), '有效事件太少，可能导致校正不准确，要继续提交吗', $ret);
        }

        $ret['status'] = 2;

        return show(config('code.success'), '待支付', $ret);
    }

    /**
     * @title 更新校准生辰
     * @method PUT
     * @desc /rectification
     * @readme /doc/md/rectification/update.md
     * @return Json
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function update()
    {
        if (!$this->request->isPut())
        {
            return show(config('code.error'), '未知操作');
        }
        // 主键id
        $id = input('param.reid/d');
        // 档案id
        $rid = input('param.rid/d');
        // 校正开始时间
        $start_time = input('param.start_time/s', null);
        // 校正结束时间
        $end_time = input('param.end_time/s', null);
        // 校准生辰事件json
        $events = input('param.events/s');
        // 检测传参 主键 || 档案id || 事件json字符串
        if (!$id || !$rid || !$events)
        {
            return show(config('code.error'), '请检查事件是否填写');
        }

        if (strtotime($start_time) === false || strtotime($end_time) === false)
        {
            return show(config('code.error'), '请检查时间是否正确');
        }

        $startTimeInter = strtotime($start_time);
        $endTimeInter = strtotime($end_time);

        $timeDiff = $endTimeInter - $startTimeInter;

        if ($timeDiff < 0)
        {
            return show(config('code.error'), '开始时间不能大于结束时间');
        }

        if ($timeDiff == 0)
        {
            return show(config('code.error'), '开始时间不能等于结束时间');
        }

        if ($timeDiff > 7200)
        {
            return show(config('code.error'), '校正范围不可超过两小时');
        }

        $ev = json_decode($events, true);

        $nowTime = time();

        foreach ($ev as $k => $v)
        {
            $vTime = isset($v['time']) ? strtotime($v['time']) : 0;
            /**
             * 校验 事件时间不能大于当前时间 && 事件时间不能小于出生时间
             */
            if ($vTime > $nowTime || $vTime < $startTimeInter)
            {
                return show(config('code.error'), '请检查事件的时间是否正确选择');
            }
        }

        // 获取用户id
        $recode = (new Recode())->getRecode(['id' => $rid]);
        if (!$recode || $recode['uid'] != $this->user['id'])
        {
            return show(config('code.error'), '档案不存在');
        }
        if ($recode['isself'] != 1)
        {
            return show(config('code.error'), '当前仅限校正自己的档案');
        }
        // 矫正范围的中点时间
        $birth_time_mid = ($startTimeInter + $endTimeInter) / 2;
        // 所有的事件
        $events_array = json_decode($events, true);

        $event_array = (new RectificationLib())->getValidEvents($events_array, $birth_time_mid, $recode);

        // 初始化有效事件数量
        $vaild_num = 0;

        foreach ($event_array as $ea)
        {
            if ($ea['status'] == 1)
            {
                $vaild_num++;
            }
        }

        //判断是否是applePay
        if ($this->is_apple_pay)
        {
            $goods = $this->apple_goods['rec_goods'][0];
        } else
        {
            $goods = (new Goods())->getGoodsRec(['id' => 1]);
        }


        if (!$goods || empty($goods))
        {
            return show(config('code.error'), '商品不存在');
        }


        // 获取活动折扣
        $activeDiscount = active($goods['id']);
        if ($activeDiscount['discount'] && !$this->is_apple_pay)
        {
            $goods['now_prize'] = sprintf("%.2f", $goods['now_prize'] * $activeDiscount['discount']);
        }

        $ret = [
            'status' => 0,
            'or_amount' => sprintf("%.2f", $goods['or_prize']),
            'total_amount' => sprintf("%.2f", $goods['now_prize']),
            'reid' => 0,
        ];

        $order_status = 0;// 默认未支付

        $orders = RectificationModel::hasWhere('Orders', ['is_del' => 0, 'reid' => $id, 'uid' => $this->user['id']])->field('order_id,trade_type,pay_time,return_time,total_amount')->find();

        // 入库  付款后 加入计算队列
        try
        {
            $update_data = [
                'rid' => $rid,
                'start_time' => $startTimeInter,
                'end_time' => $endTimeInter,
                'update_time' => time()
            ];
            (new \app\common\cachemodel\Rectification())->saveRec($this->user['id'], $id, $update_data, $event_array);
//            $rectification = RectificationModel::get($id);
//            // 存入校准生辰表
//            $rectification->isUpdate(true)->save($update_data);
//            // 删除校准生辰事件表
//            $rectification->events()->delete();
//            // 存入校准生辰事件表
//            $rectification->events()->saveAll($event_array);
            //更新校准生辰状态
//            RectificationModel::update(['status' => 0], ['id' => $id]);
            // 判断支付状态
            if ($orders && $orders->status)
            {
                // 已支付
                $order_status = 1;
            }
        }
        catch (Exception $e)
        {
            return show(config('code.error'), $e->getMessage());
        }

        $ret['reid'] = (int)($id);
        $ret['order_status'] = $order_status;

        if ($vaild_num < 1)
        {
            return show(config('code.success'), '无有效事件，会导致校正失败，请继续添加', $ret);
        }

        if ($vaild_num < 3)
        {
            $ret['status'] = 1;

            return show(config('code.success'), '有效事件太少，可能导致校正不准确，要继续提交吗', $ret);
        }

        $ret['status'] = 2;

        return show(config('code.success'), '更新成功', $ret);
    }

    /**
     * @title 校准生辰采纳
     * @method POST
     * @desc /use_rectification
     * @readme /doc/md/rectification/use.md
     * @return Json
     * @throws Exception
     */
    public function use()
    {
        if (!$this->request->isPost())
        {
            return show(config('code.error'), '未知操作');
        }
        $uid = (int)$this->user['id'];

        $id = input('id/d', 0);// 采纳的结果id
        $reid = input('reid/d', 0);// 校准生辰id

        if (!$uid || !$id || !$reid)
        {
            return show(config('code.error'), '请求错误');
        }

        $RecodeModel = new Recode();

        try
        {
            $rectification = RectificationModel::get($reid);

            if (!$rectification || $rectification['uid'] != $this->user['id'])
            {
                return show(config('code.error'), '数据不存在');
            }
            $recode = $RecodeModel->getRecode(['uid' => $this->user['id'], 'id' => $rectification->rid]);
            $rectification['result'] = $rectification->result()->where('id', $id)->find();
            $long_deg = $recode['long_deg'];
            $long_min = $recode['long_min'];
            $ew = $recode['ew'];
            $lat_deg = $recode['lat_deg'];
            $lat_min = $recode['lat_min'];
            $ns = $recode['ns'];
            $timezone = $recode['timezone'];
            $rid = $recode['id'];
        }
        catch (Exception $e)
        {
            return show(config('code.error'), $e->getMessage());
        }

        $use_time = (int)$rectification['result']['time'];// 采纳的时间 为东八区时间 转换为用户档案时区的时间

        if (date('I', $use_time) == 1)
        {
            // 若为底层判断夏令时时间，强行+1小时
            $use_time += 3600;
        }
        $datetime = new DateTime();
        $datetime->setTimestamp($use_time + $timezone * 3600);
        $datetime->setTimezone(new DateTimeZone('UTC'));
        list($year, $month, $day, $hour, $minute) = explode(',', $datetime->format('Y,m,d,H,i,s'));

        $is_summer = 0;
        // 只判断大陆地区的夏令时
        if (!in_array($recode['birth_country'], $this->noNeedJudgeSummer, false) && isSummerTime($hour, $minute, 0, $month, $day, $year))
        {
            $is_summer = 1;// 是夏令时时间
        }

        $Astro = new AstroIndex();
        $longitude = ($long_deg + $long_min / 60) * $ew;
        $latitude = ($lat_deg + $lat_min / 60) * $ns;
        // 查询当前星盘日月水金火木土等星落座落宫存入数据库
        $astro_data = $Astro->getTheRecodeAstro($year, $month, $day, $hour, $minute, $longitude, $latitude, $timezone);

        $recResModel = new RectificationResult();
        try
        {
            // 先将已采用的还原为未采用
            $recResModel->UpdateData($this->user['id'], $reid, $id);
            // 更新档案
            (new \app\common\cachemodel\Recode())->UpdateData($this->user['id'], $rid, [
                'year' => $year,
                'month' => $month,
                'day' => $day,
                'hour' => $hour,
                'minute' => $minute,
                'is_summer' => $is_summer,
                'sun' => $astro_data['sun'],
                'moon' => $astro_data['moon'],
                'asc' => $astro_data['asc'],
                'merc' => $astro_data['merc'],
                'venu' => $astro_data['venu'],
                'mars' => $astro_data['mars'],
                'jupi' => $astro_data['jupi'],
                'satu' => $astro_data['satu'],
                'non' => $astro_data['non'],
                'lili' => $astro_data['lili'],
                'juno' => $astro_data['juno'],
                'mc' => $astro_data['mc'],
            ], 1);
            // 更新档案的缓存 暂时为删除当前档案缓存
            Cache::rm('recode_' . $rid);
            Cache::rm('recode_lists_' . $uid);
            // 更新首页缓存
            // 更新首页用户星座缓存 删除这一个缓存后，会更新所有首页运势相关缓存
            //Cache::rm(FortuneCache::REDIS_KEY_HOME_SUN_IN_SIGN . $rid);
            // 更新日运详情缓存
            //Cache::rm(FortuneCache::REDIS_KEY_DETAIL_SUITABLE . $rid . '_' . strtotime(date('Y-m-d') . ' 12:00:00'));
            // （new）删除 日运缓存
            FortuneCache::rmFortuneDayCache($rid, strtotime(date('Y-m-d') . ' 12:00:00'));

            Db::table('wechat_backup_07_18_14_43_00.app_recode_info')->where('rid', $rid)->update(['last_time' => $this->request->time()]);// 更新档案最后时间

            Db::table('wechat_backup_07_18_14_43_00.app_recode_astro')->where(['rid' => $rid])->update($astro_data);// 更新档案行星数据
        }
        catch (Exception $e)
        {
            return show(config('code.error'), $e->getMessage());
        }

        $mids = [];

        try
        {
            // TODO 添加消息到消息中心封装
            // 获取校准生辰对应的消息id
            $reids = Db::table('wechat_backup_07_18_14_43_00.app_message_center')->field('id')->where('reid', $reid)->find();

            if ($reids || !empty($reids))
            {
                // 获取已读的消息id
                $msg = Db::table('app_user_msg')->where('uid', $uid)->field('mid')->select();
                if ($msg || !empty($msg))
                {
                    foreach ($msg as $k => $v)
                    {
                        $mids[] = $v['mid'];
                    }
                    if (!in_array($reids['id'], $mids, false))
                    {
                        Db::table('app_user_msg')->insert(['mid' => $reids['id'], 'uid' => $uid]);
                    }
                } else
                {
                    Db::table('app_user_msg')->insert(['mid' => $reids['id'], 'uid' => $uid]);
                }

            }
        }
        catch (Exception $e)
        {
            return show(config('code.error'), $e->getMessage());
        }

        $astro_data['rid'] = $rid;
        $astro_data['year'] = $year;
        $astro_data['month'] = $month;
        $astro_data['day'] = $day;
        $astro_data['hour'] = $hour;
        $astro_data['minute'] = $minute;
        $astro_data['is_summer'] = $is_summer;

        try
        {
            #神策打点 56 校正结果应用 RectificationResultUse
            $sensorsTrackData = [
                'max_percent' => 0,// 最佳百分比
                'result_name' => '最佳方案',// 采用方案名称
                'result_id' => $id,// 采用方案ID
                'result_percent' => 0,// 采用方案百分比
            ];
            $recResultList = $recResModel->field('id,score')->where('reid', $reid)->order('score desc')->select();
            foreach ($recResultList as $k => $v)
            {
                if ($k === 0)
                {
                    $sensorsTrackData['max_percent'] = $v['score'];
                }
                if ($id == $v['id'])
                {
                    $sensorsTrackData['result_percent'] = $v['score'];
                    if ($k > 0)
                    {
                        $sensorsTrackData['result_name'] = '推荐方案' . ($k + 1);
                    }
                }
            }
            SensorsData::track($uid, true, 'RectificationResultUse', $sensorsTrackData);
        }
        catch (\Exception $e)
        {
            Log::write('校正结果应用打点失败：' . $e->getMessage(), 'error', true);
        }

        return show(config('code.success'), '采纳成功', $astro_data);
    }
}
